<template>
  <div class="sql-editor" :class="{ 'sql-editor--focused': isFocused, 'sql-editor--readonly': isReadonly }" :style="containerStyle">
    <!-- 工具栏 -->
    <SqlToolbar
      v-if="showToolbar"
      :can-undo="canUndo"
      :can-redo="canRedo"
      :has-errors="hasErrors"
      :has-warnings="hasWarnings"
      :sql-type="sqlType"
      :character-count="characterCount"
      :line-count="lineCount"
      :has-selection="hasSelection"
      @format="handleFormat"
      @clear="handleClear"
      @undo="undo"
      @redo="redo"
      @validate="validate"
      @execute="handleExecute"
      @execute-selected="handleExecuteSelected"
    />

    <!-- 编辑器容器 -->
    <div 
      class="sql-editor__container" 
      :style="editorContainerStyle" 
      @contextmenu.prevent="showContextMenuHandler"
    >
      <!-- 行号 -->
      <div v-if="showLineNumbers" class="sql-editor__line-numbers">
        <div
          v-for="lineNumber in lineCount"
          :key="lineNumber"
          class="sql-editor__line-number"
          :class="{ 'sql-editor__line-number--current': lineNumber === currentLineNumber }"
        >
          {{ lineNumber }}
        </div>
      </div>

      <!-- 主编辑区域 -->
      <div class="sql-editor__main">
        <!-- 文本输入区域 - 放在高亮层前面 -->
        <textarea
          ref="textareaRef"
          v-model="content"
          class="sql-editor__textarea"
          :class="{
            'sql-editor__textarea--highlight': enableHighlight,
            'sql-editor__textarea--error': hasErrors
          }"
          :placeholder="placeholder"
          :readonly="isReadonly"
          :maxlength="maxLength"
          spellcheck="false"
          autocomplete="off"
          autocorrect="off"
          autocapitalize="off"
          @input="handleInput"
          @keydown="handleKeydown"
          @keyup="handleKeyup"
          @focus="handleFocus"
          @blur="handleBlur"
          @scroll="handleScroll"
          @select="handleSelect"
        />
        
        <!-- 语法高亮层 - 放在textarea后面 -->
        <div v-if="enableHighlight" class="sql-editor__highlight-container">
          <SqlHighlighter
            :content="content"
            class="sql-editor__highlight"
          />
        </div>

        <!-- 自动完成提示 -->
        <Teleport to="body">
          <div
            v-if="showAutocomplete && suggestions.length > 0"
            class="sql-editor__autocomplete"
            :style="autocompleteStyle"
            @mousedown.prevent
          >
            <div class="sql-editor__autocomplete-header">
              智能提示 ({{ suggestions.length }})
            </div>
            <div
              v-for="(suggestion, index) in suggestions"
              :key="index"
              class="sql-editor__suggestion"
              :class="{
                'sql-editor__suggestion--selected': index === selectedSuggestionIndex,
                [`sql-editor__suggestion--${suggestion.type}`]: true
              }"
              @click="applySuggestion(suggestion)"
              @mouseover="selectedSuggestionIndex = index"
            >
              <span 
                class="sql-editor__suggestion-text" 
                :title="suggestion.text"
              >
                {{ suggestion.text }}
              </span>
              <span 
                class="sql-editor__suggestion-type" 
                :title="suggestion.type.toUpperCase()"
              >
                {{ suggestion.type }}
              </span>
              <span 
                class="sql-editor__suggestion-desc" 
                :title="suggestion.description"
              >
                {{ suggestion.description }}
              </span>
            </div>
          </div>
        </Teleport>
      </div>
      
      <!-- 右键菜单 -->
      <div
        v-if="contextMenuVisible"
        class="sql-editor__context-menu"
        :style="contextMenuStyle"
        @click.stop
        @contextmenu.prevent
      >
        <div class="sql-editor__context-menu-item" @click="handleExecute">
          <span class="sql-editor__context-menu-icon">▶</span>
          执行 (F5)
        </div>
        <div class="sql-editor__context-menu-item" @click="handleFormat">
          <span class="sql-editor__context-menu-icon">⟴</span>
          格式化 (Ctrl+Shift+F)
        </div>
        <div class="sql-editor__context-menu-item" @click="handleValidate">
          <span class="sql-editor__context-menu-icon">✓</span>
          验证 (Ctrl+Shift+V)
        </div>
        <div class="sql-editor__context-menu-separator"></div>
        <div class="sql-editor__context-menu-item" @click="handleCopy" :class="{ 'sql-editor__context-menu-item--disabled': !hasSelection }">
          <span class="sql-editor__context-menu-icon">⎘</span>
          复制 (Ctrl+C)
        </div>
        <div class="sql-editor__context-menu-item" @click="handleCut" :class="{ 'sql-editor__context-menu-item--disabled': !hasSelection || isReadonly }">
          <span class="sql-editor__context-menu-icon">✂</span>
          剪切 (Ctrl+X)
        </div>
        <div class="sql-editor__context-menu-item" @click="handlePaste" :class="{ 'sql-editor__context-menu-item--disabled': isReadonly }">
          <span class="sql-editor__context-menu-icon">📋</span>
          粘贴 (Ctrl+V)
        </div>
        <div class="sql-editor__context-menu-separator"></div>
        <div class="sql-editor__context-menu-item" @click="undo" :class="{ 'sql-editor__context-menu-item--disabled': !canUndo || isReadonly }">
          <span class="sql-editor__context-menu-icon">↶</span>
          撤销 (Ctrl+Z)
        </div>
        <div class="sql-editor__context-menu-item" @click="redo" :class="{ 'sql-editor__context-menu-item--disabled': !canRedo || isReadonly }">
          <span class="sql-editor__context-menu-icon">↷</span>
          重做 (Ctrl+Y)
        </div>
        <div class="sql-editor__context-menu-separator"></div>
        <div class="sql-editor__context-menu-item" @click="toggleToolbar">
          <span class="sql-editor__context-menu-icon">{{ showToolbar ? '▼' : '▲' }}</span>
          {{ showToolbar ? '隐藏工具栏' : '显示工具栏' }}
        </div>
        <div class="sql-editor__context-menu-item" @click="handleClear" :class="{ 'sql-editor__context-menu-item--disabled': !content || isReadonly }">
          <span class="sql-editor__context-menu-icon">��</span>
          清空
        </div>
      </div>
    </div>

    <!-- 状态栏 -->
    <div v-if="showStatusBar" class="sql-editor__status">
      <div class="sql-editor__status-left">
        <span class="sql-editor__status-item">
          行 {{ currentLineNumber }}, 列 {{ currentColumnNumber }}
        </span>
        <span class="sql-editor__status-item">
          {{ characterCount }} 字符
        </span>
        <span v-if="sqlType !== 'unknown'" class="sql-editor__status-item">
          {{ sqlType.toUpperCase() }}
        </span>
      </div>
      
      <div class="sql-editor__status-right">
        <span v-if="hasErrors" class="sql-editor__status-item sql-editor__status-item--error">
          {{ validationResult.errors.length }} 错误
        </span>
        <span v-if="hasWarnings" class="sql-editor__status-item sql-editor__status-item--warning">
          {{ validationResult.warnings.length }} 警告
        </span>
        <span v-if="isDirty" class="sql-editor__status-item">
          未保存
        </span>
        <span class="sql-editor__status-item sql-editor__status-shortcut" @click="toggleToolbar">
          {{ showToolbar ? '隐藏' : '显示' }}工具栏 (F10)
        </span>
      </div>
    </div>

    <!-- 错误提示 -->
    <div v-if="showValidation && (hasErrors || hasWarnings)" class="sql-editor__validation">
      <div v-for="error in validationResult.errors" :key="error" class="sql-editor__error">
        {{ error }}
      </div>
      <div v-for="warning in validationResult.warnings" :key="warning" class="sql-editor__warning">
        {{ warning }}
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch, nextTick, onMounted, onUnmounted, Teleport } from 'vue'
import SqlToolbar from './SqlToolbar.vue'
import SqlHighlighter from './SqlHighlighter.vue'
import { formatSql, beautifySql } from './utils/sqlFormatter'
import { validateSql, getSqlType, isReadOnlyQuery } from './utils/sqlValidator'
import { getAutocompleteSuggestions, applySuggestion as applyAutocompleteSuggestion } from './utils/sqlAutocomplete'
import useSqlEditor from './composables/useSqlEditor'

// Props
const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  },
  height: {
    type: String,
    default: '300px'
  },
  placeholder: {
    type: String,
    default: '请输入SQL语句...'
  },
  readonly: {
    type: Boolean,
    default: false
  },
  showToolbar: {
    type: Boolean,
    default: true
  },
  showLineNumbers: {
    type: Boolean,
    default: true
  },
  showStatusBar: {
    type: Boolean,
    default: true
  },
  showValidation: {
    type: Boolean,
    default: true
  },
  enableHighlight: {
    type: Boolean,
    default: true
  },
  enableAutocomplete: {
    type: Boolean,
    default: true
  },
  maxLength: {
    type: Number,
    default: 50000
  },
  autoValidate: {
    type: Boolean,
    default: true
  },
  debounceTime: {
    type: Number,
    default: 300
  },
  // 数据库类型 (mysql, postgresql, sqlserver, sqlite, oracle)
  databaseType: {
    type: String,
    default: ''
  },
  // 自动完成上下文
  tables: {
    type: Array,
    default: () => []
  },
  columns: {
    type: Array,
    default: () => []
  }
})

// Emits
const emit = defineEmits([
  'update:modelValue',
  'update:showToolbar',
  'change',
  'focus',
  'blur',
  'execute',
  'execute-selected',
  'format',
  'validate'
])

// 使用SQL编辑器组合式函数
const {
  content,
  cursorPosition,
  selectionStart,
  selectionEnd,
  isReadonly,
  isFocused,
  isDirty,
  validationResult,
  sqlType,
  isQuery,
  characterCount,
  lineCount,
  hasErrors,
  hasWarnings,
  canUndo,
  canRedo,
  validate,
  format,
  insertText,
  replaceSelection,
  getSelectedText,
  getCurrentLine,
  getExecutableSql,
  clear,
  saveToHistory,
  undo,
  redo,
  cleanup
} = useSqlEditor({
  initialValue: props.modelValue,
  autoValidate: props.autoValidate,
  debounceTime: props.debounceTime,
  maxLength: props.maxLength,
  databaseType: props.databaseType
})

// 模板引用
const textareaRef = ref()

// 自动完成相关
const showAutocomplete = ref(false)
const suggestions = ref([])
const selectedSuggestionIndex = ref(0)
const autocompleteStyle = ref({})

// 右键菜单相关
const contextMenuVisible = ref(false)
const contextMenuStyle = ref({})
const hasSelection = computed(() => selectionStart.value !== selectionEnd.value)

// 工具栏显示状态
const showToolbarInternal = ref(props.showToolbar)

// 计算属性
const currentLineNumber = computed(() => {
  const lines = content.value.substring(0, cursorPosition.value).split('\n')
  return lines.length
})

const currentColumnNumber = computed(() => {
  const lines = content.value.substring(0, cursorPosition.value).split('\n')
  return lines[lines.length - 1].length + 1
})

// 容器样式
const containerStyle = computed(() => {
  return {
    display: 'flex',
    flexDirection: 'column',
    height: props.height === '100%' ? '100%' : 'auto',
    flex: props.height === '100%' ? '1' : 'none'
  }
})

// 编辑器容器样式
const editorContainerStyle = computed(() => {
  return {
    flex: '1',
    height: props.height === '100%' ? 'auto' : props.height
  }
})

// 监听器
watch(() => props.modelValue, (newValue) => {
  if (newValue !== content.value) {
    content.value = newValue
  }
})

watch(content, (newValue) => {
  emit('update:modelValue', newValue)
  emit('change', newValue)
})

watch(() => props.readonly, (newValue) => {
  isReadonly.value = newValue
})

watch(() => props.showToolbar, (newValue) => {
  showToolbarInternal.value = newValue
})

watch(showToolbarInternal, (newValue) => {
  emit('update:showToolbar', newValue)
})

// 事件处理
const handleInput = (event) => {
  updateCursorPosition()
  
  if (props.enableAutocomplete) {
    updateAutocomplete()
  }
}

const handleKeydown = (event) => {
  // 处理快捷键
  if (event.key === 'F5') {
    // F5 执行
    event.preventDefault()
    handleExecute()
    return
  }

  if (event.key === 'F10') {
    // F10 切换工具栏
    event.preventDefault()
    toggleToolbar()
    return
  }

  if (event.key === 'Escape') {
    // ESC 隐藏自动完成和右键菜单
    if (showAutocomplete.value) {
      hideAutocomplete()
      event.preventDefault()
      return
    }
    
    if (contextMenuVisible.value) {
      hideContextMenu()
      event.preventDefault()
      return
    }
  }

  // Ctrl/Command组合键
  if (event.ctrlKey || event.metaKey) {
    switch (event.key) {
      case 'z':
        event.preventDefault()
        if (event.shiftKey) {
          redo()
        } else {
          undo()
        }
        break
      case 'y':
        event.preventDefault()
        redo()
        break
      case 'f':
        if (event.shiftKey) {
          // Ctrl+Shift+F 格式化
          event.preventDefault()
          handleFormat()
        }
        break
      case 'v':
        if (event.shiftKey) {
          // Ctrl+Shift+V 验证
          event.preventDefault()
          handleValidate()
        } else {
          // 正常粘贴功能，不拦截
        }
        break
      case 'Enter':
        // Ctrl+Enter 执行选中的SQL
        event.preventDefault()
        if (hasSelection.value) {
          handleExecuteSelected()
        } else {
          handleExecute()
        }
        break
      case 'r':
        // Ctrl+R 执行
        event.preventDefault()
        handleExecute()
        break
    }
  }

  // 处理自动完成
  if (showAutocomplete.value && suggestions.value.length > 0) {
    switch (event.key) {
      case 'ArrowDown':
        event.preventDefault()
        selectedSuggestionIndex.value = Math.min(
          selectedSuggestionIndex.value + 1,
          suggestions.value.length - 1
        )
        break
      case 'ArrowUp':
        event.preventDefault()
        selectedSuggestionIndex.value = Math.max(selectedSuggestionIndex.value - 1, 0)
        break
      case 'Enter':
      case 'Tab':
        event.preventDefault()
        applySuggestion(suggestions.value[selectedSuggestionIndex.value])
        break
      case 'Escape':
        hideAutocomplete()
        break
    }
  }

  // Tab键处理
  if (event.key === 'Tab' && !showAutocomplete.value) {
    event.preventDefault()
    insertText('  ') // 插入两个空格
  }

  // 保存历史记录
  if (event.key === ' ' || event.key === 'Enter') {
    saveToHistory()
  }
}

const handleKeyup = (event) => {
  updateCursorPosition()
  updateSelection()
}

const handleFocus = () => {
  isFocused.value = true
  emit('focus')
}

const handleBlur = () => {
  isFocused.value = false
  hideAutocomplete()
  emit('blur')
}

const handleScroll = () => {
  // 同步高亮层滚动
  if (props.enableHighlight && textareaRef.value) {
    const highlightContainer = document.querySelector('.sql-editor__highlight-container')
    if (highlightContainer) {
      highlightContainer.scrollTop = textareaRef.value.scrollTop
      highlightContainer.scrollLeft = textareaRef.value.scrollLeft
    }
  }
}

const handleSelect = () => {
  updateSelection()
}

const handleFormat = () => {
  const success = format()
  emit('format', { success, content: content.value })
}

const handleClear = () => {
  if (content.value && content.value.trim()) {
    if (confirm('确定要清空编辑器内容吗？此操作不可撤销。')) {
      clear()
    }
  } else {
    clear()
  }
}

const handleExecute = () => {
  saveToHistory()
  emit('execute', content.value)
}

const handleExecuteSelected = () => {
  if (hasSelection.value) {
    saveToHistory()
    const selectedSql = getSelectedText()
    emit('execute-selected', selectedSql)
  } else {
    handleExecute()
  }
}

const handleValidate = () => {
  const result = validate()
  emit('validate', result)
}

// 切换工具栏显示
const toggleToolbar = () => {
  showToolbarInternal.value = !showToolbarInternal.value
  hideContextMenu()
}

// 右键菜单
const showContextMenuHandler = (event) => {
  event.preventDefault()
  
  // 更新选择状态
  updateSelection()
  
  // 设置菜单位置
  contextMenuStyle.value = {
    position: 'absolute',
    left: `${event.offsetX}px`,
    top: `${event.offsetY}px`,
    zIndex: 1000
  }
  
  // 显示菜单
  contextMenuVisible.value = true
  
  // 添加全局点击监听器以关闭菜单
  window.addEventListener('click', hideContextMenu)
  window.addEventListener('contextmenu', hideContextMenu)
  
  return false
}

const hideContextMenu = () => {
  contextMenuVisible.value = false
  window.removeEventListener('click', hideContextMenu)
  window.removeEventListener('contextmenu', hideContextMenu)
}

// 剪贴板操作
const handleCopy = () => {
  if (hasSelection.value && textareaRef.value) {
    document.execCommand('copy')
  }
}

const handleCut = () => {
  if (hasSelection.value && !isReadonly.value && textareaRef.value) {
    document.execCommand('cut')
  }
}

const handlePaste = () => {
  if (!isReadonly.value && textareaRef.value) {
    document.execCommand('paste')
  }
}

// 辅助方法
const updateCursorPosition = () => {
  if (textareaRef.value) {
    cursorPosition.value = textareaRef.value.selectionStart
  }
}

const updateSelection = () => {
  if (textareaRef.value) {
    selectionStart.value = textareaRef.value.selectionStart
    selectionEnd.value = textareaRef.value.selectionEnd
  }
}

const updateAutocomplete = () => {
  if (!props.enableAutocomplete) return

  const context = {
    tables: props.tables,
    columns: props.columns,
    dbType: props.databaseType
  }

  const newSuggestions = getAutocompleteSuggestions(
    content.value,
    cursorPosition.value,
    context
  )

  if (newSuggestions.length > 0) {
    suggestions.value = newSuggestions
    selectedSuggestionIndex.value = 0
    showAutocomplete.value = true
    updateAutocompletePosition()
  } else {
    hideAutocomplete()
  }
}

const updateAutocompletePosition = () => {
  if (!textareaRef.value) return

  // 计算自动完成提示的位置
  const textarea = textareaRef.value
  const rect = textarea.getBoundingClientRect()
  
  // 计算光标位置
  const textBeforeCursor = content.value.substring(0, cursorPosition.value)
  const lines = textBeforeCursor.split('\n')
  const currentLine = lines[lines.length - 1]
  
  // 创建一个临时元素来测量文本宽度
  const measureEl = document.createElement('span')
  measureEl.style.visibility = 'hidden'
  measureEl.style.position = 'absolute'
  measureEl.style.whiteSpace = 'pre'
  measureEl.style.font = getComputedStyle(textarea).font
  measureEl.textContent = currentLine
  document.body.appendChild(measureEl)
  
  const lineHeight = parseInt(getComputedStyle(textarea).lineHeight) || 20
  const charWidth = measureEl.offsetWidth / (currentLine.length || 1)
  
  document.body.removeChild(measureEl)
  
  // 计算相对于文本区域的坐标
  const relativeX = (currentLine.length * charWidth) % (textarea.clientWidth - 40)
  const relativeY = (lines.length - 1) * lineHeight - textarea.scrollTop + 20
  
  // 转换为页面绝对坐标
  let left = rect.left + relativeX + window.scrollX
  let top = rect.top + relativeY + lineHeight + window.scrollY
  
  // 检查是否会超出右侧边界
  const viewportWidth = window.innerWidth
  if (left + 320 > viewportWidth) { // 320px是下拉框的宽度
    left = Math.max(0, viewportWidth - 320)
  }
  
  // 检查是否会超出底部边界
  const viewportHeight = window.innerHeight
  const dropdownBottom = top + 240 // 240px是下拉框的最大高度
  
  if (dropdownBottom > viewportHeight + window.scrollY) {
    // 如果下拉框超出了视口底部，则将其显示在光标上方
    top = rect.top + relativeY - 240 + window.scrollY // 减去下拉框高度
    top = Math.max(window.scrollY, top) // 确保不会超出顶部
  }
  
  // 使用固定定位，这样滚动时不会移动
  autocompleteStyle.value = {
    position: 'fixed',
    left: `${left - window.scrollX}px`,
    top: `${top - window.scrollY}px`,
    maxHeight: '240px',
    width: '320px',
    zIndex: 9999
  }
}

const applySuggestion = (suggestion) => {
  const result = applyAutocompleteSuggestion(content.value, cursorPosition.value, suggestion)
  content.value = result.input
  
  nextTick(() => {
    if (textareaRef.value) {
      textareaRef.value.setSelectionRange(result.cursorPosition, result.cursorPosition)
      cursorPosition.value = result.cursorPosition
      textareaRef.value.focus() // 确保应用建议后保持焦点
    }
  })
  
  hideAutocomplete()
}

const hideAutocomplete = () => {
  showAutocomplete.value = false
  suggestions.value = []
  selectedSuggestionIndex.value = 0
}

// 全局键盘事件处理
const handleGlobalKeyDown = (event) => {
  if (event.key === 'F10') {
    event.preventDefault()
    toggleToolbar()
  }
  
  if (event.key === 'Escape') {
    if (contextMenuVisible.value) {
      hideContextMenu()
    }
  }
}

// 生命周期
onMounted(() => {
  if (props.readonly) {
    isReadonly.value = true
  }
  
  // 添加全局键盘事件监听
  window.addEventListener('keydown', handleGlobalKeyDown)
})

onUnmounted(() => {
  cleanup()
  
  // 移除全局键盘事件监听
  window.removeEventListener('keydown', handleGlobalKeyDown)
  
  // 清理可能残留的事件监听器
  window.removeEventListener('click', hideContextMenu)
  window.removeEventListener('contextmenu', hideContextMenu)
})

// 暴露方法给父组件
defineExpose({
  focus: () => textareaRef.value?.focus(),
  blur: () => textareaRef.value?.blur(),
  insertText,
  replaceSelection,
  getSelectedText,
  getCurrentLine,
  getExecutableSql,
  format: handleFormat,
  clear: handleClear,
  validate,
  undo,
  redo,
  execute: handleExecute,
  toggleToolbar
})

// 将自动完成提示移动到body中，避免被其他元素遮挡
const moveToBody = (el) => {
  if (el && document.body) {
    document.body.appendChild(el)
  }
}

const removeFromBody = (el) => {
  if (el && el.parentNode === document.body) {
    document.body.removeChild(el)
  }
}
</script>

<style scoped>
.sql-editor {
  display: flex;
  flex-direction: column;
  border: 1px solid #e5e7eb;
  border-radius: 6px;
  background: #ffffff;
  font-family: 'JetBrains Mono', 'Consolas', 'Monaco', monospace;
  min-height: 0; /* 修复Flexbox布局在某些浏览器中的溢出问题 */
  width: 100%;
}

.sql-editor--focused {
  border-color: #3b82f6;
  box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.1);
}

.sql-editor--readonly {
  background: #f9fafb;
}

.sql-editor__container {
  display: flex;
  flex: 1;
  position: relative;
  overflow: hidden;
}

.sql-editor__line-numbers {
  display: flex;
  flex-direction: column;
  background: #f8fafc;
  border-right: 1px solid #e5e7eb;
  padding: 8px 4px;
  min-width: 40px;
  text-align: right;
  user-select: none;
}

.sql-editor__line-number {
  height: 20px;
  line-height: 20px;
  font-size: 12px;
  color: #9ca3af;
  padding: 0 4px;
}

.sql-editor__line-number--current {
  color: #3b82f6;
  font-weight: 500;
}

.sql-editor__main {
  flex: 1;
  position: relative;
  overflow: hidden;
  isolation: isolate; /* 创建新的层叠上下文 */
}

.sql-editor__highlight-container {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  pointer-events: none;
  overflow: auto;
  z-index: 1;
}

.sql-editor__highlight {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  padding: 8px 12px;
  font-family: inherit;
  font-size: 14px;
  line-height: 20px;
  white-space: pre-wrap;
  word-wrap: break-word;
  pointer-events: none;
  z-index: 1;
  tab-size: 2;
  background: transparent;
  user-select: none;
  box-sizing: border-box;
}

.sql-editor__textarea {
  position: relative;
  width: 100%;
  height: 100%;
  border: none;
  outline: none;
  resize: none;
  padding: 8px 12px;
  font-family: inherit;
  font-size: 14px;
  line-height: 20px;
  background: transparent;
  color: #374151;
  tab-size: 2;
  z-index: 2;
  white-space: pre-wrap;
  word-wrap: break-word;
  overflow: auto;
}

.sql-editor__textarea--highlight {
  color: transparent;
  caret-color: #374151;
}

.sql-editor__textarea--error {
  border-left: 3px solid #ef4444;
}

.sql-editor__autocomplete {
  position: absolute;
  background: #ffffff;
  border: 1px solid #e5e7eb;
  border-radius: 6px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  max-height: 240px;
  overflow-y: auto;
  z-index: 9999;
  width: 320px;
  font-size: 13px;
}

.sql-editor__autocomplete-header {
  padding: 6px 10px;
  background-color: #f8fafc;
  border-bottom: 1px solid #e5e7eb;
  color: #64748b;
  font-size: 11px;
  font-weight: 500;
  border-top-left-radius: 6px;
  border-top-right-radius: 6px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.sql-editor__suggestion {
  display: flex;
  align-items: center;
  padding: 5px 10px;
  cursor: pointer;
  border-bottom: 1px solid #f3f4f6;
  transition: background-color 0.1s ease;
}

.sql-editor__suggestion:last-child {
  border-bottom: none;
}

.sql-editor__suggestion--selected {
  background: #eff6ff;
}

.sql-editor__suggestion:hover {
  background: #f3f4f6;
}

.sql-editor__suggestion:active {
  background: #e5e7eb;
}

.sql-editor__suggestion-text {
  font-weight: 600;
  margin-right: 8px;
  font-size: 13px;
  min-width: 80px;
  max-width: 120px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  position: relative;
}

.sql-editor__suggestion-type {
  font-size: 11px;
  color: #6b7280;
  margin-right: 8px;
  text-transform: uppercase;
  background: #f3f4f6;
  padding: 2px 4px;
  border-radius: 3px;
  min-width: 50px;
  text-align: center;
  position: relative;
}

.sql-editor__suggestion-desc {
  font-size: 12px;
  color: #9ca3af;
  flex: 1;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  position: relative;
}

/* 使用CSS原生tooltip实现更好的提示效果 */
.sql-editor__suggestion-text[title]::after,
.sql-editor__suggestion-type[title]::after,
.sql-editor__suggestion-desc[title]::after {
  content: attr(title);
  position: absolute;
  bottom: calc(100% + 5px);
  left: 0;
  background: rgba(0, 0, 0, 0.8);
  color: white;
  border-radius: 4px;
  padding: 4px 8px;
  font-size: 12px;
  white-space: nowrap;
  z-index: 10000;
  pointer-events: none;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.2);
  max-width: 300px;
  overflow: hidden;
  text-overflow: ellipsis;
  opacity: 0;
  visibility: hidden;
  transition: opacity 0.2s, visibility 0.2s;
}

.sql-editor__suggestion-text[title]:hover::after,
.sql-editor__suggestion-type[title]:hover::after,
.sql-editor__suggestion-desc[title]:hover::after {
  opacity: 1;
  visibility: visible;
  transition-delay: 0.3s;
}

.sql-editor__suggestion--keyword .sql-editor__suggestion-text {
  color: #7c3aed;
}

.sql-editor__suggestion--table .sql-editor__suggestion-text {
  color: #059669;
}

.sql-editor__suggestion--column .sql-editor__suggestion-text {
  color: #dc2626;
}

.sql-editor__suggestion--function .sql-editor__suggestion-text {
  color: #ea580c;
}

.sql-editor__suggestion--keyword .sql-editor__suggestion-type {
  background-color: #f3e8ff;
  color: #7c3aed;
}

.sql-editor__suggestion--table .sql-editor__suggestion-type {
  background-color: #dcfce7;
  color: #059669;
}

.sql-editor__suggestion--column .sql-editor__suggestion-type {
  background-color: #fee2e2;
  color: #dc2626;
}

.sql-editor__suggestion--function .sql-editor__suggestion-type {
  background-color: #fff7ed;
  color: #ea580c;
}

.sql-editor__status {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 4px 12px;
  background: #f8fafc;
  border-top: 1px solid #e5e7eb;
  font-size: 12px;
  height: 28px;
}

.sql-editor__status-left {
  display: flex;
  align-items: center;
}

.sql-editor__status-right {
  display: flex;
  align-items: center;
}

.sql-editor__status-item {
  margin-right: 16px;
  color: #6b7280;
}

.sql-editor__status-item:last-child {
  margin-right: 0;
}

.sql-editor__status-item--error {
  color: #ef4444;
}

.sql-editor__status-item--warning {
  color: #f59e0b;
}

.sql-editor__status-shortcut {
  cursor: pointer;
  padding: 2px 6px;
  border-radius: 4px;
  transition: background-color 0.2s;
}

.sql-editor__status-shortcut:hover {
  background-color: #e5e7eb;
  color: #374151;
}

.sql-editor__validation {
  padding: 8px 12px;
  background: #fef2f2;
  border-top: 1px solid #fecaca;
  max-height: 120px;
  overflow-y: auto;
}

.sql-editor__error {
  color: #ef4444;
  font-size: 12px;
  margin-bottom: 4px;
}

.sql-editor__warning {
  color: #f59e0b;
  font-size: 12px;
  margin-bottom: 4px;
}

.sql-editor__context-menu {
  position: absolute;
  background: #ffffff;
  border: 1px solid #e5e7eb;
  border-radius: 6px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  overflow-y: auto;
  z-index: 1000;
  min-width: 200px;
  padding: 4px 0;
}

.sql-editor__context-menu-item {
  display: flex;
  align-items: center;
  padding: 8px 12px;
  cursor: pointer;
  font-size: 13px;
  color: #374151;
}

.sql-editor__context-menu-item:hover {
  background: #f3f4f6;
}

.sql-editor__context-menu-icon {
  margin-right: 8px;
  font-size: 14px;
  width: 20px;
  display: inline-flex;
  justify-content: center;
}

.sql-editor__context-menu-item--disabled {
  color: #9ca3af;
  cursor: not-allowed;
}

.sql-editor__context-menu-item--disabled:hover {
  background: transparent;
}

.sql-editor__context-menu-separator {
  height: 1px;
  background: #e5e7eb;
  margin: 4px 0;
}

/* 为不同的元素设置不同的tooltip位置 */
.sql-editor__suggestion-type[title]::after {
  left: 50%;
  transform: translateX(-50%);
}

.sql-editor__suggestion-desc[title]::after {
  right: 0;
  left: auto;
}
</style> 